package cn.com.czpb.client.module.personal.acticity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.custorm.CircleImageView;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.model.news.CommEntity;
import cn.com.czpb.client.model.usercenter.UserEntity;
import cn.com.czpb.client.module.news.dialog.ReplyDialog;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.module.personal.adapter.DynamicsAdapter;
import cn.com.czpb.client.module.personal.widget.TranslucentListener;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class PersonPageActivity extends AppCompatActivity implements BaseQuickAdapter.OnItemChildClickListener,
        BaseQuickAdapter.RequestLoadMoreListener, TranslucentListener {
    @BindView(R.id.title_stilte_layout)
    TextView title_toolbar;

    //    @BindView(R.id.photo_activity_person_page)
    CircleImageView photo_activity_person_page;
    //    @BindView(R.id.introduce_activity_person)
    TextView introduce_activity_person;
    //    @BindView(R.id.user_name_activity_person)
    TextView user_name_activity_person;
    //    @BindView(R.id.tv_lv_person)
    TextView tv_lv_person;
    //    @BindView(R.id.tv_count)
    TextView tv_count;
    //    @BindView(R.id.edit_activity_page)
    LinearLayout edit_activity_page;
    @BindView(R.id.stitle_layout)
    RelativeLayout stitle_layout;
    @BindView(R.id.recycler_person)
    RecyclerView recycler_person;
    //
    private List<CommBean> list;
    private DynamicsAdapter adapter;
    private String uid;
    int Page = 1;
    int PageSize = 15;
    boolean mFlagRefresh;
    private SPUtil spu;
LoginQuitBR br;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_persin_page);

        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WodeFragment.ACTION_QUIT);
        filter.addAction(WodeFragment.ACTION_USER);
        filter.addAction(WodeFragment.ACTION_QUIT_LOGIN);

        registerReceiver(br, filter);

        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        spu = SPUtil.getInstance();
        list = new ArrayList<>();
        title_toolbar.setText("个人主页");
        uid = getIntent().getStringExtra("uid");
        adapter = new DynamicsAdapter(list, this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_person.setLayoutManager(manager);

        recycler_person.setAdapter(adapter);
        adapter.addHeaderView(getHeaderView(1, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.edit_activity_page:

                        break;
                }
            }
        }));
//        toolbar.setBackgroundColor(getResources().getColor(R.color.black));
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, recycler_person);
//        scrollView.setListener(this);
        LogUtils.e("person--" + uid);
        init();
        initList();

    }

    private void initList() {

        Map<String, String> map = new HashMap<>();

        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("uid", uid);
        map.put("deivce", DeviceUtils.getMyUUID(this));
        Factory.provideHttpService().UserDyNamic(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommEntity, Boolean>() {
                    @Override
                    public Boolean call(CommEntity commEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommEntity>() {
                    @Override
                    public void call(CommEntity commEntity) {
                        if (mFlagRefresh) {
                            mFlagRefresh = false;
                        }
                        LogUtils.e("code---" + commEntity.code);
                        if (commEntity.code.equals("200")) {

                            setListData(commEntity.data);
                            tv_count.setText("动态(" + commEntity.data.size() + ")");
                            LogUtils.e("code" + commEntity.data.size() + "");

                            adapter.notifyDataSetChanged();
                        } else {
//                            TUtils.toast(commEntity.msg);
                        }
                    }
                });
    }

    @OnClick(R.id.back_stitle_layout)
    public void goback(View view) {
        finish();
    }

    public void setListData(List<CommBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < PageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }

    private void init() {
        if (spu.getUser()!=null){
            Glide.with(PersonPageActivity.this).load(spu.getUser().getAvatar_path()).into(photo_activity_person_page);
        }

        if (spu.getUser() != null) {
            if (uid.equals(spu.getUser().getUid())) {
                edit_activity_page.setVisibility(View.VISIBLE);
            }
        }else {
            edit_activity_page.setVisibility(View.GONE);
        }
        Map<String, String> map = new HashMap<>();

        map.put("uid", uid);
        Factory.provideHttpService().getUserInfo(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.i("200--login" + userEntity.code);
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if ("200".equals(userEntity.code)) {
                            Glide.with(PersonPageActivity.this).load(userEntity.data.getAvatar_path())
                                    .into(photo_activity_person_page);
                            user_name_activity_person.setText(TextUtils.getLengthText(userEntity.data.getNickname(), 8));
                            introduce_activity_person.setText("介绍：" + TextUtils.getLengthText(userEntity.data.getDesc(), 8));
                            tv_lv_person.setText(userEntity.data.getUlevel());
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    private void sendComment(String content, String cid, String nid, String type) {

        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", type);
        map.put("title", nid);
        map.put("content", content);
        map.put("cid", cid);
        map.put("json_url", "fsdfsdfsfs");//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {

                        if ("200".equals(entity.code)) {
                            TUtils.toast("评论成功");
//                            et_reply.setText("");
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");

                    }
                });
    }

    @OnClick(R.id.edit_activity_page)
    public void click(View view) {
        switch (view.getId()) {

        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
        final CommBean obj = (CommBean) adapter1.getItem(position);
        ReplyDialog dialog = new ReplyDialog(this, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
            @Override
            public void inputstr(String string) {
                sendComment(string, obj.getData().getCid(), obj.getData().getNid(), obj.getData().getType());
            }
        });
        dialog.show();
        initList();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadMoreRequested() {
        Page++;
        initList();
    }

    @Override
    public void onTranlucent(float alpha) {

    }

    private View getHeaderView(int type, View.OnClickListener listener) {
        View view = getLayoutInflater().inflate(R.layout.header_person, (ViewGroup) recycler_person.getParent(), false);
        photo_activity_person_page = view.findViewById(R.id.photo_activity_person_page);
        introduce_activity_person = view.findViewById(R.id.introduce_activity_person);
        user_name_activity_person = view.findViewById(R.id.user_name_activity_person);
        tv_lv_person = view.findViewById(R.id.tv_lv_person);
        tv_count = view.findViewById(R.id.tv_count);
        edit_activity_page = view.findViewById(R.id.edit_activity_page);
        edit_activity_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonPageActivity.this, AccountSetActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }


    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WodeFragment.ACTION_USER)) {
                setLogin();
            } else if (action.equals(WodeFragment.ACTION_QUIT)) {
                setQuit();
                LogUtils.i("setquit");
            } else if (action.equals(WodeFragment.ACTION_QUIT_LOGIN)) {
                setQuit();
                LogUtils.i("setquitlogin");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        zy_rfrag_ll_login.callOnClick();
                        LogUtils.i("r_login_layout.callOnClick()");
                    }
                }, 500);
            }
        }
    }


    private void setLogin() {
        Glide.with(PersonPageActivity.this).load(spu.getUser().getAvatar_path()).into(photo_activity_person_page);
        user_name_activity_person.setText(spu.getUser().getNickname());
        introduce_activity_person.setText("介绍：" +spu.getUser().getDesc());
        tv_lv_person.setText(spu.getUser().getUlevel());
    }
    private void setQuit() {
    }

}
